package com.frank.im.db;

import java.util.ArrayList;

import android.content.Context;

import com.frank.im.base.ImCallback;
import com.frank.im.base.ImChatManage;
import com.frank.im.base.ImConstant;
import com.frank.im.base.ImServiceConnection;
import com.frank.im.bean.GetUserInfo;
import com.frank.im.bean.ImReqData;
import com.frank.im.bean.ImRespData;
import com.frank.im.bean.ImRespStatusData;
import com.frank.im.bean.MsgCont;
import com.frank.im.bean.MsgContExp;
import com.frank.im.bean.SendMsg;
import com.frank.im.bean.ServiceMarkRead;
import com.frank.im.bean.ServiceMsgCont;
import com.frank.im.bean.ServiceSysMsg;
import com.frank.im.bean.ServiceUserInfo;
import com.frank.im.bean.SessionRecord;
import com.frank.im.bean.SysMsgCont;
import com.frank.im.bean.UserTemp;
import com.frank.im.utils.ImDataUtils;
import com.frank.im.utils.Logger;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * im通讯数据管理
 * 
 * @author Frank
 * @version 1.0 Create by 2016.4.11
 */
public class ImDBManage {
	private final static String TAG = ImDBManage.class.getSimpleName();
	private static ImDBManage dbMg = new ImDBManage();

	private ImDBManage() {
	}

	public synchronized static ImDBManage getInstance() {
		return dbMg;
	}

	public synchronized boolean dealAllResp(String content) {
		boolean flag = false;
		Gson respGson = null;
		ImRespData respData = null;
		try {
			respGson = new Gson();
			respData = respGson.fromJson(content, new TypeToken<ImRespData>() {
			}.getType());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		if (respData != null) {
			flag = allResponse(respData);
		}
		return flag;

	}

	/**
	 * 所有响应处理
	 * 
	 * @param respData
	 * @param message
	 */
	public synchronized boolean allResponse(ImRespData respData) {
		boolean flag = false;
		ImRespStatusData<?> imRespStatusData = null;
		Gson respGson = new Gson();
		String respStatusDataStr = "";
		if (respData != null) {
			respStatusDataStr = respData.data;
			Logger.i(TAG, "respStatusDataStr：" + respStatusDataStr);
			try {
				if (respStatusDataStr != null && !respStatusDataStr.equals("")) {
					imRespStatusData = respGson.fromJson(respStatusDataStr,
							new TypeToken<ImRespStatusData<?>>() {
							}.getType());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imRespStatusData != null && imRespStatusData.state
					&& imRespStatusData.code == 200) {
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 处理消息内容
	 * 
	 * @param respData
	 */
	public synchronized void dealSysMsg(Context ctx, ImRespData respData) {
		ImRespStatusData<ServiceSysMsg> imRespStatusData = null;
		Gson respGson = null;
		String respStatusDataStr = "";
		if (respData != null) {
			respStatusDataStr = respData.data;
			try {
				if (respStatusDataStr != null && !respStatusDataStr.equals("")) {
					respGson = new Gson();
					imRespStatusData = respGson.fromJson(respStatusDataStr,
							new TypeToken<ImRespStatusData<ServiceSysMsg>>() {
							}.getType());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imRespStatusData != null && imRespStatusData.state
					&& imRespStatusData.code == 200
					&& imRespStatusData.data != null
					&& imRespStatusData.data.size() > 0) {
				inserSysMsg(ctx, respData.request_id, imRespStatusData.data);
			}
		}
	}

	/**
	 * 插入系统消息内容
	 * 
	 * @param requestId
	 * @param serviceMsgConts
	 */
	public synchronized void inserSysMsg(Context ctx, String requestId,
			ArrayList<ServiceSysMsg> serviceSysMsgs) {
		for (ServiceSysMsg serviceSysMsg : serviceSysMsgs) {
			SysMsgCont sysMsgCont = new SysMsgCont();
			sysMsgCont.serviceContId = serviceSysMsg.sys_msg_id;
			sysMsgCont.sendTime = String.valueOf(serviceSysMsg.add_time);
			sysMsgCont.cont = serviceSysMsg.content;
			sysMsgCont.readStatus = 0;

			// 用户是否存在
			if (!ImDaoImpl.getInstance().isExists(0, "0")) {
				/*** 获取用户信息 ***/
				insertOrUpdateUser(0, "系统消息", "http://www.doubi.com/");
			}

			// 消息是否已经存在
			if (!ImDaoImpl.getInstance().isExists(5,
					String.valueOf(sysMsgCont.serviceContId))) {
				long msgNum = -1;
				msgNum = ImDaoImpl.getInstance().insertSysMsgCont(sysMsgCont);
				if (msgNum != -1) {
					sessionRecordDeal(sysMsgCont);
				}
			}
		}
	}

	/**
	 * 插入用户信息
	 * 
	 * @param userTemp
	 */
	public synchronized void insertOrUpdateUser(int userId, String userName,
			String headImg) {
		UserTemp userTemp = new UserTemp();
		userTemp.userId = userId;
		userTemp.userName = userName;
		userTemp.headImg = headImg;
		// 用户是否存在
		if (!ImDaoImpl.getInstance().isExists(1, String.valueOf(userId))) {
			/*** 获取用户信息 ***/
			ImDaoImpl.getInstance().insertUserTemp(userTemp);
		} else {
			ImDaoImpl.getInstance().updateUserInfo(userTemp);
		}
	}

	/**
	 * 消息记录表数据处理
	 * 
	 * @param serviceMsgConts
	 */
	public synchronized void sessionRecordDeal(SysMsgCont sysMsgCont) {
		if (ImDaoImpl.getInstance().isExists(2, "0")) {
			int noReadNum = -1;
			noReadNum = ImDaoImpl.getInstance().getNoreadNum(2, "0");
			if (noReadNum != -1) {
				ImDaoImpl.getInstance().updateSessionReadStatus(noReadNum,
						String.valueOf("0"));
			}
			ImDaoImpl.getInstance().updateSessionCont(sysMsgCont.cont,
					sysMsgCont.sendTime, "0");
		} else {
			int noReadNum = -1;
			noReadNum = ImDaoImpl.getInstance().getNoreadNum(2, "0");
			SessionRecord sessionRecord = new SessionRecord();
			if (noReadNum != -1) {
				sessionRecord.noReadNum = noReadNum;
				sessionRecord.userId = 0;
				sessionRecord.newCont = sysMsgCont.cont;
				sessionRecord.newContTime = sysMsgCont.sendTime;
			}
			ImDaoImpl.getInstance().insertSessionRecord(sessionRecord);
		}
	}

	/**
	 * 处理消息内容
	 * 
	 * @param respData
	 */
	public synchronized void dealMsgCont(Context ctx, ImRespData respData) {
		ImRespStatusData<ServiceMsgCont> imRespStatusData = null;
		Gson respGson = null;
		String respStatusDataStr = "";
		if (respData != null) {
			respStatusDataStr = respData.data;
			try {
				if (respStatusDataStr != null && !respStatusDataStr.equals("")) {
					respGson = new Gson();
					imRespStatusData = respGson.fromJson(respStatusDataStr,
							new TypeToken<ImRespStatusData<ServiceMsgCont>>() {
							}.getType());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imRespStatusData != null && imRespStatusData.state
					&& imRespStatusData.code == 200
					&& imRespStatusData.data != null
					&& imRespStatusData.data.size() > 0) {
				inserMsgCont(ctx, respData.request_id, imRespStatusData.data);
			}
		}
	}

	/**
	 * 插入消息内容
	 * 
	 * @param requestId
	 * @param serviceMsgConts
	 */
	public synchronized void inserMsgCont(Context ctx, String requestId,
			ArrayList<ServiceMsgCont> serviceMsgConts) {
		for (ServiceMsgCont serviceMsgCont : serviceMsgConts) {
			MsgContExp contExp = new MsgContExp();
			contExp.expType = 1;
			contExp.cont = serviceMsgCont.content;
			contExp.fromId = serviceMsgCont.send_user_id;
			contExp.toId = Integer.parseInt(ImChatManage.getInstance()
					.getAppMarkUtil().getUserId());

			MsgCont msgCont = new MsgCont();
			msgCont.requestId = requestId;
			msgCont.fromId = serviceMsgCont.send_user_id;
			msgCont.toId = Integer.parseInt(ImChatManage.getInstance()
					.getAppMarkUtil().getUserId());
			msgCont.serviceContId = serviceMsgCont.id;
			msgCont.readStatus = 0;
			msgCont.sendStatus = 2;
			msgCont.sendTime = Long.toString(serviceMsgCont.add_time);
			msgCont.isShowTime = 1;
			msgCont.msgContType = 1;

			// 用户是否存在
			if (!ImDaoImpl.getInstance().isExists(1,
					String.valueOf(serviceMsgCont.send_user_id))) {
				/*** 获取用户信息 ***/
				getUserInfo(ctx, serviceMsgCont.send_user_id);
			}

			// 消息是否已经存在
			if (!ImDaoImpl.getInstance().isExists(3,
					String.valueOf(serviceMsgCont.id))) {
				long msgNum = -1;
				msgNum = ImDaoImpl.getInstance()
						.insertMsgCont(msgCont, contExp);
				if (msgNum != -1) {
					sessionRecordDeal(serviceMsgCont);
				}
			}
		}
	}

	/**
	 * 消息记录表数据处理
	 * 
	 * @param serviceMsgConts
	 */
	public synchronized void sessionRecordDeal(ServiceMsgCont serviceMsgCont) {
		if (ImDaoImpl.getInstance().isExists(2,
				String.valueOf(serviceMsgCont.send_user_id))) {
			int noReadNum = -1;
			noReadNum = ImDaoImpl.getInstance().getNoreadNum(1,
					String.valueOf(serviceMsgCont.send_user_id),
					String.valueOf(0));
			if (noReadNum != -1) {
				ImDaoImpl.getInstance().updateSessionReadStatus(noReadNum,
						String.valueOf(serviceMsgCont.send_user_id));
			}
			ImDaoImpl.getInstance().updateSessionCont(serviceMsgCont.content,
					String.valueOf(serviceMsgCont.add_time),
					String.valueOf(serviceMsgCont.send_user_id));
		} else {
			int noReadNum = -1;
			noReadNum = ImDaoImpl.getInstance().getNoreadNum(1,
					String.valueOf(serviceMsgCont.send_user_id));
			SessionRecord sessionRecord = new SessionRecord();
			if (noReadNum != -1) {
				sessionRecord.noReadNum = noReadNum;
				sessionRecord.userId = serviceMsgCont.send_user_id;
				sessionRecord.newCont = serviceMsgCont.content;
				sessionRecord.newContTime = String
						.valueOf(serviceMsgCont.add_time);
			}
			ImDaoImpl.getInstance().insertSessionRecord(sessionRecord);
		}
	}

	/**
	 * 处理用户信息
	 * 
	 * @param respData
	 */
	public synchronized void getUserInfo(Context ctx, final int userId) {
		GetUserInfo userInfo = new GetUserInfo();
		userInfo.user_id = userId;
		ImServiceConnection.getInstance().send(ctx, ImConstant.GET_USER_INFO,
				ImDataUtils.getUserInfo(userInfo), new ImCallback() {

					@Override
					public void onStart() {

					}

					@Override
					public void onSuccess(String content) {
						Logger.i(TAG, "getUserInfo:" + content);
						dealUser(userId, content);
					}

					@Override
					public void onFailure(String content) {

					}

				});
	}

	/**
	 * 处理用户信息
	 * 
	 * @param respData
	 */
	public synchronized void dealUser(int userId, String content) {
		ImRespData respData = null;
		ImRespStatusData<ServiceUserInfo> imRespStatusData = null;
		String respStatusDataStr = "";
		Gson respGson = null;
		try {
			respGson = new Gson();
			respData = respGson.fromJson(content, new TypeToken<ImRespData>() {
			}.getType());
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (respData != null) {
			respStatusDataStr = respData.data;
			try {
				if (respStatusDataStr != null && !respStatusDataStr.equals("")) {
					respGson = new Gson();
					imRespStatusData = respGson.fromJson(respStatusDataStr,
							new TypeToken<ImRespStatusData<ServiceUserInfo>>() {
							}.getType());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imRespStatusData != null && imRespStatusData.state
					&& imRespStatusData.code == 200
					&& imRespStatusData.data != null
					&& imRespStatusData.data.size() > 0) {
				insertOrUpdateUser(userId, imRespStatusData.data);
			}
		}
	}

	/**
	 * 插入用户信息
	 * 
	 * @param userTemp
	 */
	public synchronized void insertOrUpdateUser(int userId,
			ArrayList<ServiceUserInfo> serviceUserInfos) {
		for (ServiceUserInfo serviceUserInfo : serviceUserInfos) {
			UserTemp userTemp = new UserTemp();
			// userTemp.userId = serviceUserInfo.userId;
			userTemp.userId = userId;
			userTemp.userName = serviceUserInfo.nickname;
			userTemp.headImg = serviceUserInfo.head_img;
			// 用户是否存在
			if (!ImDaoImpl.getInstance().isExists(1, String.valueOf(userId))) {
				/*** 获取用户信息 ***/
				ImDaoImpl.getInstance().insertUserTemp(userTemp);
			} else {
				ImDaoImpl.getInstance().updateUserInfo(userTemp);
			}
		}
	}

	/**
	 * 发送消息
	 * 
	 * @param respData
	 */
	public synchronized void sendMsg(Context ctx, String content) {
		ImReqData imReqData = null;
		Gson reqGson = null;
		SendMsg sendMsg = null;
		String reqDataStr = "";
		if (content != null && !content.equals("")) {
			try {
				reqGson = new Gson();
				imReqData = reqGson.fromJson(content,
						new TypeToken<ImReqData>() {
						}.getType());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imReqData != null) {
				reqDataStr = imReqData.getData();
			}
			if (reqDataStr != null && !reqDataStr.equals("")) {
				if (reqGson == null) {
					reqGson = new Gson();
				}
				sendMsg = reqGson.fromJson(reqDataStr,
						new TypeToken<SendMsg>() {
						}.getType());

			}
			if (sendMsg != null) {
				Long timeL = System.currentTimeMillis() / 1000;
				String time = Long.toString(timeL);
				MsgContExp contExp = new MsgContExp();
				contExp.expType = 1;
				contExp.cont = sendMsg.send_msg;
				contExp.fromId = Integer.parseInt(ImChatManage.getInstance()
						.getAppMarkUtil().getUserId());
				contExp.toId = sendMsg.to_uid;

				MsgCont msgCont = new MsgCont();
				msgCont.requestId = imReqData.getRequest_id();
				msgCont.fromId = Integer.parseInt(ImChatManage.getInstance()
						.getAppMarkUtil().getUserId());
				msgCont.toId = sendMsg.to_uid;
				msgCont.serviceContId = 0;
				msgCont.readStatus = 1;
				msgCont.sendStatus = 1;
				msgCont.sendTime = time;
				msgCont.isShowTime = 1;
				msgCont.msgContType = 1;

				// 用户是否存在
				if (!ImDaoImpl.getInstance().isExists(1,
						String.valueOf(sendMsg.to_uid))) {
					/*** 获取用户信息 ***/
					getUserInfo(ctx, sendMsg.to_uid);
				}

				long msgNum = -1;
				msgNum = ImDaoImpl.getInstance()
						.insertMsgCont(msgCont, contExp);
				if (msgNum != -1) {
					ServiceMsgCont serviceMsgCont = new ServiceMsgCont();
					serviceMsgCont.send_user_id = sendMsg.to_uid;
					serviceMsgCont.content = sendMsg.send_msg;
					serviceMsgCont.add_time = Long.parseLong(time);
					sessionRecordDeal(serviceMsgCont);
				}
			}
		}
	}

	/**
	 * 处理发送失败
	 * 
	 * @param respData
	 */
	public synchronized void dealSendFailed() {
		ImDaoImpl.getInstance().updateMsgContSendFailed();
	}

	/**
	 * 处理响应发送消息内容
	 * 
	 * @param respData
	 */
	public synchronized void dealSendResp(Context ctx, ImRespData respData) {
		ImRespStatusData<ServiceMsgCont> imRespStatusData = null;
		Gson respGson = null;
		String respStatusDataStr = "";
		if (respData != null) {
			respStatusDataStr = respData.data;
			try {
				if (respStatusDataStr != null && !respStatusDataStr.equals("")) {
					respGson = new Gson();
					imRespStatusData = respGson.fromJson(respStatusDataStr,
							new TypeToken<ImRespStatusData<ServiceMsgCont>>() {
							}.getType());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imRespStatusData != null && imRespStatusData.state
					&& imRespStatusData.code == 200
					&& imRespStatusData.data != null
					&& imRespStatusData.data.size() > 0) {
				updateMsgCont(respData.request_id, imRespStatusData.data);
			}
		}
	}

	/**
	 * 更新发送信息
	 * 
	 * @param userTemp
	 */
	public synchronized void updateMsgCont(String requestId,
			ArrayList<ServiceMsgCont> serviceMsgConts) {
		for (ServiceMsgCont serviceMsgCont : serviceMsgConts) {
			if (ImDaoImpl.getInstance().isExists(4, requestId)) {
				boolean updateStatus = false;
				updateStatus = ImDaoImpl.getInstance().updateMsgContServiceId(
						serviceMsgCont.id, requestId);
				if (updateStatus) {
					Logger.i(TAG, "开始更新发送消息的数据库");
					ImDaoImpl.getInstance().updateMsgContSendStatus(2,
							requestId);
					Logger.i(TAG, "更新发送消息的数据库成功");
				}
			}
		}
	}

	/**
	 * 处理响应标记消息已读
	 * 
	 * @param respData
	 */
	public synchronized void dealMarkMsgResp(Context ctx, ImRespData respData) {
		ImRespStatusData<ServiceMarkRead> imRespStatusData = null;
		Gson respGson = null;
		String respStatusDataStr = "";
		if (respData != null) {
			respStatusDataStr = respData.data;
			try {
				if (respStatusDataStr != null && !respStatusDataStr.equals("")) {
					respGson = new Gson();
					imRespStatusData = respGson.fromJson(respStatusDataStr,
							new TypeToken<ImRespStatusData<ServiceMarkRead>>() {
							}.getType());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (imRespStatusData != null && imRespStatusData.state
					&& imRespStatusData.code == 200
					&& imRespStatusData.data != null
					&& imRespStatusData.data.size() > 0) {
				updateMsgReadStatus(imRespStatusData.data);
			}
		}
	}

	/**
	 * 更新消息已读状态
	 * 
	 * @param userTemp
	 */
	public synchronized void updateMsgReadStatus(
			ArrayList<ServiceMarkRead> serviceMarkReads) {
		for (ServiceMarkRead serviceMarkRead : serviceMarkReads) {
			if (ImDaoImpl.getInstance().isExists(3,
					String.valueOf(serviceMarkRead.sContId))) {
				boolean updateStatus = false;
				updateStatus = ImDaoImpl.getInstance().updateMsgContReadStatus(
						1, String.valueOf(serviceMarkRead.userId),
						String.valueOf(serviceMarkRead.sContId));
				if (updateStatus) {
					int noReadNum = -1;
					noReadNum = ImDaoImpl.getInstance().getNoreadNum(1,
							String.valueOf(serviceMarkRead.userId),
							String.valueOf(0));
					if (noReadNum != -1) {
						ImDaoImpl.getInstance().updateSessionReadStatus(
								noReadNum,
								String.valueOf(serviceMarkRead.userId));
					}
				}
			}
		}
	}

	/**
	 * 更新消息已读状态
	 * 
	 * @param userTemp
	 */
	public synchronized void updateMsgReadStatus(int sContId, int userId) {
		if (ImDaoImpl.getInstance().isExists(3, String.valueOf(sContId))) {
			boolean updateStatus = false;
			updateStatus = ImDaoImpl.getInstance().updateMsgContReadStatus(1,
					String.valueOf(userId), String.valueOf(sContId));
			if (updateStatus) {
				int noReadNum = -1;
				noReadNum = ImDaoImpl.getInstance().getNoreadNum(1,
						String.valueOf(userId), String.valueOf(0));
				if (noReadNum != -1) {
					ImDaoImpl.getInstance().updateSessionReadStatus(noReadNum,
							String.valueOf(userId));
				}
			}
		}
	}

	/**
	 * 更新系统消息已读状态
	 * 
	 * @param userTemp
	 */
	public synchronized void updateSysMsgReadStatus(int sContId) {
		if (ImDaoImpl.getInstance().isExists(5, String.valueOf(sContId))) {
			boolean updateStatus = false;
			updateStatus = ImDaoImpl.getInstance().updateMsgContReadStatus(2,
					String.valueOf(sContId));
			if (updateStatus) {
				int noReadNum = -1;
				noReadNum = ImDaoImpl.getInstance().getNoreadNum(2,
						String.valueOf(0));
				if (noReadNum != -1) {
					ImDaoImpl.getInstance().updateSessionReadStatus(noReadNum,
							String.valueOf(0));
				}
			}
		}
	}

}
